<?php

require_once __DIR__ . '/vendor/autoload.php';

$app = require_once __DIR__ . '/bootstrap/app.php';
$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

try {
    echo "🔧 开始修复菜单权限和补齐数据...\n";

    // 1. 确保超级管理员角色存在并有正确权限
    $superAdminRole = \DB::table('roles')->where('code', 'super_admin')->first();
    if (!$superAdminRole) {
        \DB::table('roles')->insert([
            'name' => '超级管理员',
            'code' => 'super_admin',
            'description' => '系统超级管理员，拥有所有权限',
            'type' => 'system',
            'status' => 'active',
            'sort_order' => 1,
            'permissions' => json_encode(['*']),
            'created_at' => now(),
            'updated_at' => now(),
        ]);
        echo "✅ 创建超级管理员角色\n";
    } else {
        // 更新超级管理员权限
        \DB::table('roles')->where('code', 'super_admin')->update([
            'permissions' => json_encode(['*']),
            'updated_at' => now(),
        ]);
        echo "🔄 更新超级管理员权限\n";
    }

    // 2. 补齐缺失的菜单数据
    $menus = [
        // 菜单管理子菜单
        [
            'parent_id' => 2, // 系统管理菜单ID
            'name' => '菜单管理',
            'code' => 'menu_manage',
            'icon' => 'menu',
            'path' => '/system/menus',
            'component' => 'MenuManage',
            'type' => 'page',
            'description' => '管理系统菜单',
            'permissions' => json_encode(['menu.manage']),
            'status' => 'active',
            'is_visible' => true,
            'sort_order' => 3,
        ],
        // 系统日志子菜单
        [
            'parent_id' => 2,
            'name' => '系统日志',
            'code' => 'system_log',
            'icon' => 'file-text',
            'path' => '/system/logs',
            'component' => 'SystemLog',
            'type' => 'page',
            'description' => '查看系统操作日志',
            'permissions' => json_encode(['system.log']),
            'status' => 'active',
            'is_visible' => true,
            'sort_order' => 4,
        ],
        // 岗位管理子菜单
        [
            'parent_id' => 3, // 人事管理菜单ID
            'name' => '岗位管理',
            'code' => 'position_manage',
            'icon' => 'briefcase',
            'path' => '/hr/positions',
            'component' => 'PositionManage',
            'type' => 'page',
            'description' => '管理岗位信息',
            'permissions' => json_encode(['position.manage']),
            'status' => 'active',
            'is_visible' => true,
            'sort_order' => 3,
        ],
        // 个人中心菜单
        [
            'parent_id' => null,
            'name' => '个人中心',
            'code' => 'profile',
            'icon' => 'user',
            'path' => '/profile',
            'component' => 'ProfileLayout',
            'type' => 'menu',
            'description' => '个人相关功能',
            'permissions' => json_encode(['profile.view']),
            'status' => 'active',
            'is_visible' => true,
            'sort_order' => 4,
        ],
    ];

    // 首先创建个人中心菜单
    $profileMenuId = null;
    foreach ($menus as $menuData) {
        if ($menuData['code'] === 'profile') {
            $existingMenu = \DB::table('menus')->where('code', $menuData['code'])->first();
            if (!$existingMenu) {
                $profileMenuId = \DB::table('menus')->insertGetId(array_merge($menuData, [
                    'created_at' => now(),
                    'updated_at' => now(),
                ]));
                echo "✅ 创建菜单：{$menuData['name']}\n";
            } else {
                $profileMenuId = $existingMenu->id;
            }
            break;
        }
    }

    // 创建其他菜单
    foreach ($menus as $menuData) {
        if ($menuData['code'] !== 'profile') {
            $existingMenu = \DB::table('menus')->where('code', $menuData['code'])->first();

            if (!$existingMenu) {
                \DB::table('menus')->insert(array_merge($menuData, [
                    'created_at' => now(),
                    'updated_at' => now(),
                ]));
                echo "✅ 创建菜单：{$menuData['name']}\n";
            }
        }
    }

    // 创建个人信息和修改密码子菜单
    if ($profileMenuId) {
        $profileSubMenus = [
            [
                'parent_id' => $profileMenuId,
                'name' => '个人信息',
                'code' => 'profile_info',
                'icon' => 'user-circle',
                'path' => '/profile/info',
                'component' => 'ProfileInfo',
                'type' => 'page',
                'description' => '查看和编辑个人信息',
                'permissions' => json_encode(['profile.view']),
                'status' => 'active',
                'is_visible' => true,
                'sort_order' => 1,
            ],
            [
                'parent_id' => $profileMenuId,
                'name' => '修改密码',
                'code' => 'change_password',
                'icon' => 'lock',
                'path' => '/profile/password',
                'component' => 'ChangePassword',
                'type' => 'page',
                'description' => '修改登录密码',
                'permissions' => json_encode(['profile.edit']),
                'status' => 'active',
                'is_visible' => true,
                'sort_order' => 2,
            ],
        ];

        foreach ($profileSubMenus as $menuData) {
            $existingMenu = \DB::table('menus')->where('code', $menuData['code'])->first();
            if (!$existingMenu) {
                \DB::table('menus')->insert(array_merge($menuData, [
                    'created_at' => now(),
                    'updated_at' => now(),
                ]));
                echo "✅ 创建子菜单：{$menuData['name']}\n";
            }
        }
    }

    // 3. 确保管理员用户存在并分配超级管理员角色
    $adminUser = \DB::table('users')->where('username', 'admin')->first();
    if (!$adminUser) {
        $userId = \DB::table('users')->insertGetId([
            'username' => 'admin',
            'phone' => '13800000000',
            'password' => \Illuminate\Support\Facades\Hash::make('admin123'),
            'status' => 'active',
            'preferences' => json_encode([
                'language' => 'zh_CN',
                'theme' => 'light',
                'timezone' => 'Asia/Shanghai',
            ]),
            'created_at' => now(),
            'updated_at' => now(),
        ]);
        echo "✅ 创建管理员用户\n";
    } else {
        $userId = $adminUser->id;
    }

    // 分配超级管理员角色
    $superAdminRole = \DB::table('roles')->where('code', 'super_admin')->first();
    if ($superAdminRole) {
        $existingAssignment = \DB::table('user_roles')
            ->where('user_id', $userId)
            ->where('role_id', $superAdminRole->id)
            ->first();

        if (!$existingAssignment) {
            \DB::table('user_roles')->insert([
                'user_id' => $userId,
                'role_id' => $superAdminRole->id,
                'start_date' => now(),
                'status' => 'active',
                'assigned_at' => now(),
                'reason' => '系统初始化',
                'created_at' => now(),
                'updated_at' => now(),
            ]);
            echo "✅ 为管理员用户分配超级管理员角色\n";
        }
    }

    // 4. 创建根部门
    $rootDept = \DB::table('departments')->where('code', 'HQ')->first();
    if (!$rootDept) {
        \DB::table('departments')->insert([
            'name' => '公司总部',
            'code' => 'HQ',
            'description' => '公司总部，最高层级部门',
            'status' => 'active',
            'sort_order' => 1,
            'created_at' => now(),
            'updated_at' => now(),
        ]);
        echo "✅ 创建根部门\n";
    }

    echo "🎉 菜单权限修复和数据补齐完成！\n";
    echo "\n📋 超级管理员账户：\n";
    echo "用户名：admin\n";
    echo "密码：admin123\n";
    echo "权限：所有权限（包括所有菜单访问权限）\n";

} catch (Exception $e) {
    echo "❌ 错误：" . $e->getMessage() . "\n";
    echo "📍 文件：" . $e->getFile() . " 行：" . $e->getLine() . "\n";
}
